﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
//using MySql.Data;
using MySql.Data.MySqlClient;
using System.Text.RegularExpressions;
using System.Threading;
#if!__MonoCS__
using Outlook = Microsoft.Office.Interop.Outlook;
using Microsoft.Office.Interop.Outlook;
#endif
using System.Security.Principal;
using System.Configuration;

namespace Contacts
{
    public partial class ContactsAddEdit : Form
    {
        private DataSet dscont;
        private DataSet compare;
        private DataGridView dgv;
        public BindingSource compbs;
        private int contact_id;
        int compsi;
        int compsv;
        int comid;
        int pref;
        public int nc = 0;
        object compid;
        CompaniesAddEdit compe;
        CompaniesAddEdit compn;
        ContactsAddEdit csf;        
        DataView contview;
        MySqlConn connect = new MySqlConn();
        //update conn = new update();
        DialogResult resultpf;
        DialogResult resultpar;
        Mess mess;
        public string phone;
        public string digit;
        public string num;
        public string p1;
        public string p2;
        public string np;
        public bool b;
        public bool click;
        int pos;
        string condition;
        bool newcont;
        DataRowView contid;
        DataRow cont = null;
        DataTable original = new DataTable();
        DataTable currentcont = new DataTable();
        DataRow currentrow;
        DataTable currentcomp = new DataTable();
        DataRow origrow;
        string pulltime;
        MySqlConnection connection = new MySqlConnection();
        string database;
        FormCollection forms = System.Windows.Forms.Application.OpenForms;
        DataTable updated = new DataTable();
        compare compform = new compare();
        DataSet chgeddata;
        DataRow updaterow;
        protected const string traceout = "ContactsTrace";
		    protected Microsoft.Exchange.WebServices.Authentication.TraceListener tracer;
        
        #region constructors
        
        //this edits an existing contact
        public ContactsAddEdit(DataSet contacts, BindingSource contactsbs, int contact_id, string tablename, DataGridView grd_jr_cont, string topull, ContactsAddEdit contform)
            
        {
            InitializeComponent();
            tracer = new Microsoft.Exchange.WebServices.Authentication.TraceListener();tracer.Trace(traceout, string.Format("{0}Contacts Form Initialized","\r\n"));
            dscont = contacts;            
            compbs = contactsbs;
            dgv = grd_jr_cont;
            pulltime = topull;tracer.Trace(traceout, string.Format("Time of Pull: {0}",pulltime));

            try
            {
                if (dgv != null)
                {
                    pos = contact_id;
                    contsel.Visible = false;
                    cbo_contsel.Visible = false;
                    link.Visible = false;
                    but_addcont.Visible = false;
                }

                cbo_company.DataSource = compbs;
                cbo_company.ValueMember = "companies.company_id";
                cbo_company.DisplayMember = "companies.comp_sel";
                DataRow csiv = contacts.Tables["contacts"].Rows.Find(pos);
                DataRow compsiv = contacts.Tables["companies"].Rows.Find(csiv.ItemArray[5].ToString());
                string name = compsiv["comp_sel"].ToString();
                cbo_company.SelectedIndex = cbo_company.FindStringExact(name);
                tbo_first_name.Text = csiv["first_name"].ToString();
                tbo_middle_name.Text = csiv["middle_name"].ToString();
                tbo_last_name.Text = csiv["last_name"].ToString();
                tbo_job_title.Text = csiv["job_title"].ToString();

                if (!String.IsNullOrEmpty(csiv["direct_phone"].ToString()) || csiv["direct_phone"].ToString() == "() -  Ext: ")
                {
                    phone = csiv["direct_phone"].ToString();
                    phone = func.removecharacters(phone);
                    tbo_d1.Text = func.area(phone);
                    tbo_d2.Text = func.prefix(phone);
                    tbo_d3.Text = func.line(phone);
                    tbo_d4.Text = func.ext(phone);
                }

                if (!String.IsNullOrEmpty(csiv["mobile_phone"].ToString()))
                {
                    phone = csiv["mobile_phone"].ToString();
                    phone = func.removecharacters(phone);
                    tbo_m1.Text = func.area(phone);
                    tbo_m2.Text = func.prefix(phone);
                    tbo_m3.Text = func.line(phone);
                }
                tbo_email.Text = csiv["email"].ToString();
            }
            catch (System.Exception ex)
            {
                string subject = "ContactForm Load Existing Contact Error";
                ErrorHandling.ErrorEmail(subject, ex);
            }
        }

        //this enters a new contact
        public ContactsAddEdit(DataSet contacts, BindingSource contactsbs, string tablename, DataGridView grd_jr_cont)
        {
            try
            {
                InitializeComponent();
                dscont = contacts;
                compbs = contactsbs;
                pos = 0;
                dgv = grd_jr_cont;

                if (dgv != null)
                {
                    contsel.Visible = false;
                    cbo_contsel.Visible = false;
                    link.Visible = false;
                    but_addcont.Visible = false;
                }

                //some of this code was modified from original to allow for the contact form to load independent of store contact form
                else if (dgv == null)
                {
                    DataColumn fullname = contacts.Tables["contacts"].Columns.Add("full_name");
                    int fni;
                    int jrc = contacts.Tables["contacts"].Rows.Count;
                    for (fni = 0; fni < jrc; fni++)
                    {
                        DataRow row = contacts.Tables["contacts"].Rows[fni];
                        string mn = row["middle_name"].ToString();

                        if (String.IsNullOrEmpty(mn))
                            row["full_name"] = row["first_name"].ToString() + ' ' + row["last_name"].ToString();
                        else
                            row["full_name"] = row["first_name"].ToString() + ' ' + row["middle_name"].ToString() + ' ' + row["last_name"].ToString();
                    }

                    DataColumn compsel = contacts.Tables["companies"].Columns.Add("comp_sel");

                    //this creates a company name by location for selector in the contacts form
                    int m;
                    int mrc = contacts.Tables["companies"].Rows.Count;
                    for (m = 0; m < mrc; m++)
                    {
                        DataRow row = contacts.Tables["companies"].Rows[m];
                        row["comp_sel"] = row["company_name"] + ", " + row["street"] + ", " + row["city"] + ", " + row["state"];
                    }

                    contacts.Tables["contacts"].DefaultView.Sort = "full_name";
                    cbo_contsel.DataSource = contacts.Tables["contacts"];
                    cbo_contsel.ValueMember = "contact_id";
                    cbo_contsel.DisplayMember = "full_name";
                    cbo_contsel.SelectedIndex = -1;
                    //the below requires a single thread for this to work
                    cbo_contsel.AutoCompleteSource = AutoCompleteSource.ListItems;
                    cbo_contsel.AutoCompleteMode = AutoCompleteMode.Suggest;
                }

                cbo_company.DataSource = contactsbs;
                cbo_company.ValueMember = "companies.company_id";
                cbo_company.DisplayMember = "companies.comp_sel";
                cbo_company.SelectedIndex = -1;
                cbo_company.AutoCompleteSource = AutoCompleteSource.ListItems;
                cbo_company.AutoCompleteMode = AutoCompleteMode.Suggest;
            }
            catch (System.Exception ex)
            {
                string subject = "ContactForm Load New Contact Error";
                ErrorHandling.ErrorEmail(subject, ex);
            }
        }

        //this button clears all of the contact combo boxes and text boxes.
        private void but_addcont_Click(object sender, EventArgs e)
        {           
            cbo_contsel.DisplayMember = "";
            pos = 0;
            tbo_first_name.Text = "";
            tbo_middle_name.Text = "";
            tbo_last_name.Text = "";
            tbo_job_title.Text = "";
            cbo_company.SelectedIndex = -1;
            tbo_d1.Text = "";
            tbo_d2.Text = "";
            tbo_d3.Text = "";
            tbo_d4.Text = "";
            tbo_m1.Text = "";
            tbo_m2.Text = "";
            tbo_m3.Text = "";
            tbo_email.Text = "";
            link.Text = "";
            cbo_contsel.SelectedIndex = -1;
            tbo_first_name.Focus();
        }

        private void but_request_Click(object sender, EventArgs e)
        {
            MessageBox.Show("This is currently under construction.", "Under Construction", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        //this fills all of the combo boxes and text boxes with information from the contact select combobox
        private void cbo_contsel_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                contid = (DataRowView)cbo_contsel.SelectedItem;
                if (contid != null)
                {
                    pos = (int)contid.Row["contact_id"];
                    tbo_first_name.Text = contid.Row["first_name"].ToString();
                    tbo_middle_name.Text = contid.Row["middle_name"].ToString();
                    tbo_last_name.Text = contid.Row["last_name"].ToString();
                    tbo_job_title.Text = contid.Row["job_title"].ToString();
                    int comid = (int)contid.Row["company_id"];
                    DataRow comsiv = dscont.Tables["companies"].Rows.Find(comid);
                    cbo_company.SelectedValue = (int)comsiv["company_id"];

                    if (!String.IsNullOrEmpty(contid.Row["direct_phone"].ToString()) || contid.Row["direct_phone"].ToString() == "() -  Ext: ")
                    {
                        phone = contid.Row["direct_phone"].ToString();
                        phone = func.removecharacters(phone);
                        tbo_d1.Text = func.area(phone);
                        tbo_d2.Text = func.prefix(phone);
                        tbo_d3.Text = func.line(phone);
                        tbo_d4.Text = func.ext(phone);
                    }

                    if (!String.IsNullOrEmpty(contid.Row["mobile_phone"].ToString()))
                    {
                        phone = contid.Row["mobile_phone"].ToString();
                        phone = func.removecharacters(phone);
                        tbo_m1.Text = func.area(phone);
                        tbo_m2.Text = func.prefix(phone);
                        tbo_m3.Text = func.line(phone);
                    }
                    tbo_email.Text = contid.Row["email"].ToString();
                    link.Text = contid.Row["email"].ToString();
                    cbo_contsel.Focus();
                }

                else
                {
                    tbo_first_name.Text = "";
                    tbo_middle_name.Text = "";
                    tbo_last_name.Text = "";
                    tbo_job_title.Text = "";
                    cbo_company.SelectedIndex = -1;
                    tbo_d1.Text = "";
                    tbo_d2.Text = "";
                    tbo_d3.Text = "";
                    tbo_d4.Text = "";
                    tbo_m1.Text = "";
                    tbo_m2.Text = "";
                    tbo_m3.Text = "";
                    tbo_email.Text = "";
                    link.Text = "";
                }
            }
            catch (System.Exception ex)
            {
                string subject = "ContactForm Contact Selected Index Change Error";
                ErrorHandling.ErrorEmail(subject, ex);
            }
        }

        //this is the email link that you can click to send an email direct from the contact form.
        private void link_Click(object sender, EventArgs e)
        {
#if!__MonoCS__
            Outlook.Application ol = (Outlook.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Outlook.Application");
            Outlook._MailItem olm = (Outlook._MailItem)ol.CreateItem(Outlook.OlItemType.olMailItem);
#endif
            string email = contid.Row["email"].ToString();
#if!__MonoCS__
            olm.To = email;
            olm.Display();
#endif
        }

        private void tbo_first_name_Leave(object sender, EventArgs e)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                if (tbo_first_name.Text.Length >= 1)
                {
                    string name = tbo_first_name.Text.Trim();
                    string[] n = name.Split(' ');
                    int nl = n.Length;
                    if (nl == 1)
                    {
                        tbo_first_name.Text = tbo_first_name.Text.Substring(0, 1).ToUpper().Trim() + tbo_first_name.Text.Substring(1).Trim();
                    }
                    else
                    {
                        for (int ni = 0; ni < nl; ni++)
                        {
                            string namesplit = n[ni].Trim();
                            namesplit = namesplit.Substring(0, 1).ToUpper().Trim() + namesplit.Substring(1).Trim();

                            if (ni == 0)
                            {
                                sb.Insert(0, namesplit);
                            }
                            else
                            {
                                sb.Append(" " + namesplit);
                            }
                        }
                        tbo_first_name.Text = sb.ToString();
                    }
                }

                if (!Regex.IsMatch(tbo_first_name.Text, @"^([a-zA-Z\-\.\'\' ']{1,30})$") && !String.IsNullOrEmpty(tbo_first_name.Text))
                {
                    MessageBox.Show("You have entered invalid characters or length > 30.  " +
                         "Please re-enter the information.", "Invalid Characters", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    tbo_first_name.Clear();
                    tbo_first_name.Focus();
                }
            }
            catch (System.Exception ex)
            {
                string subject = "ContactForm First Name Leave Error";
                ErrorHandling.ErrorEmail(subject, ex);
            }
        }

        private void tbo_first_name_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Return)
            {ProcessTabKey(true);}
        }             
        
        private void tbo_middle_name_Leave(object sender, EventArgs e)
        {
            if (tbo_middle_name.Text.Length >= 1)
            {tbo_middle_name.Text = tbo_middle_name.Text.Substring(0, 1).ToUpper().Trim() + '.';}

            if (!Regex.IsMatch(tbo_middle_name.Text, @"^[a-zA-Z\.]{1,2}$") && !String.IsNullOrEmpty(tbo_middle_name.Text))
            {
                MessageBox.Show("You have entered invalid character.  " +
                     "Characters must be single letter.  " +
                     "Please re-enter the information.", "Invalid Characters", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                tbo_middle_name.Clear();
                tbo_middle_name.Focus();
            }            
        }

        private void tbo_middle_name_KeyPress(object sender, KeyPressEventArgs e)
       {
            if (e.KeyChar == (char)Keys.Return)
            {ProcessTabKey(true);}
        }

        //this checks for any existing contacts and warns user so as to not duplicate contacts
        private void tbo_last_name_Leave(object sender, EventArgs e)        
        {
            connect.Connect("contacts");
            connect.LoadTable("contacts", ref currentcont);
            connect.LoadTable("companies", ref currentcomp);
            connect.Disconnect();

            try
            {

                StringBuilder sb = new StringBuilder();
                if (tbo_last_name.Text.Length >= 1)
                {
                    string name = tbo_last_name.Text.Trim();
                    string[] n = name.Split(' ');
                    int nl = n.Length;
                    if (nl == 1)
                    {
                        tbo_last_name.Text = tbo_last_name.Text.Substring(0, 1).ToUpper() + tbo_last_name.Text.Substring(1);
                    }
                    else
                    {
                        for (int ni = 0; ni < nl; ni++)
                        {
                            string namesplit = n[ni];
                            namesplit = namesplit.Substring(0, 1).ToUpper() + namesplit.Substring(1);

                            if (ni == 0)
                            {
                                sb.Insert(0, namesplit);
                            }
                            else
                            {
                                sb.Append(" " + namesplit);
                            }
                        }
                        tbo_last_name.Text = sb.ToString();
                    }
                }

                if (!Regex.IsMatch(tbo_last_name.Text, @"^[a-zA-Z\-\.\'\' ']{1,30}$") && !String.IsNullOrEmpty(tbo_last_name.Text))
                {
                    MessageBox.Show("You have entered invalid characters or length > 30.  " +
                         "Please re-enter the information.", "Invalid Characters", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    tbo_last_name.Clear();
                    tbo_last_name.Focus();
                }

                //DataRow[] contcompare = dscont.Tables["contacts"].Select
                DataRow[] contcompare = currentcont.Select
                    (string.Format("{0} like '%{1}%' and {2} like '%{3}%'", "first_name",
                    tbo_first_name.Text.Replace("'", "''"), "last_name", tbo_last_name.Text.Replace("'", "''")));

                if (cbo_contsel.SelectedIndex == -1)
                {
                    pos = 0;
                }


                if (contcompare != null && pos == 0)
                {

                    int count = contcompare.Count();
                    int i;
                    for (i = 0; i < count; i++)
                    {
                        DataRow compname = currentcomp.Rows.Find(contcompare[i].ItemArray[5]);
                        bool mn = (contcompare[i].ItemArray[2] != string.Empty);
                        bool tit = (contcompare[i].ItemArray[4] != string.Empty);
                        bool suite = (compname.ItemArray[3] != string.Empty);

                        switch (mn)
                        {
                            case true:
                                {
                                    switch (count)
                                    {
                                        case 1:
                                            {
                                                switch (tit)
                                                {
                                                    case true:
                                                        {
                                                            switch (suite)
                                                            {
                                                                case true:
                                                                    {
                                                                        var result = MessageBox.Show("There is (1) contact that match what you entered " +
                                                                        "in the first and last name boxes.\n\n" + contcompare[i]["first_name"] + " " +
                                                                        contcompare[i]["midde_name"] + " " + contcompare[i]["last_name"] + "\n" +
                                                                        contcompare[i]["job_title"] + "\n" + compname["company_name"] + "\n" +
                                                                        compname["street"] + ", " + compname["suite"] + "\n" +
                                                                        compname["city"] + ", " + compname["state"] + " " + compname["zip"] +
                                                                        "\n\nDoes this contact match what you were planning on entering? \n" +
                                                                        "\nThere is a possibility this contact was added after your data pull so refresh \n" +
                                                                        "your data by closing/re-opening contacts after answering question.",
                                                                        "Contact Found", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);



                                                                        switch (result)
                                                                        {
                                                                            case System.Windows.Forms.DialogResult.Yes:
                                                                                { this.Close(); }
                                                                                return;
                                                                            case System.Windows.Forms.DialogResult.No:
                                                                                {
                                                                                    if (i == count)
                                                                                    { return; }
                                                                                    break;
                                                                                }
                                                                            case System.Windows.Forms.DialogResult.Cancel:
                                                                                { this.Close(); }
                                                                                return;
                                                                        }
                                                                    }
                                                                    break;
                                                                case false:
                                                                    {
                                                                        var result = MessageBox.Show("There is (1) contact that match what you entered " +
                                                                        "in the first and last name boxes.\n\n" + contcompare[i]["first_name"] + " " +
                                                                        contcompare[i]["middle_name"] + " " + contcompare[i]["last_name"] + "\n" +
                                                                        contcompare[i]["job_title"] + "\n" + compname["company_name"] + "\n" +
                                                                        compname["street"] + "\n" + compname["city"] + ", " +
                                                                        compname["state"] + " " + compname["zip"] +
                                                                        "\n\nDoes this contact match what you were planning on entering? \n" +
                                                                        "\nThere is a possibility this contact was added after your data pull so refresh \n" +
                                                                        "your data by closing/re-opening contacts after answering question.",
                                                                        "Contact Found", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

                                                                        switch (result)
                                                                        {
                                                                            case System.Windows.Forms.DialogResult.Yes:
                                                                                { this.Close(); }
                                                                                return;
                                                                            case System.Windows.Forms.DialogResult.No:
                                                                                {
                                                                                    if (i == count)
                                                                                    { return; }
                                                                                    break;
                                                                                }
                                                                            case System.Windows.Forms.DialogResult.Cancel:
                                                                                { this.Close(); }
                                                                                return;
                                                                        }
                                                                    }
                                                                    break;
                                                            }
                                                        }
                                                        break;
                                                    case false:
                                                        {
                                                            switch (suite)
                                                            {
                                                                case true:
                                                                    {
                                                                        var result = MessageBox.Show("There is (1) contact that match what you entered " +
                                                                        "in the first and last name boxes.\n\n" + contcompare[i]["first_name"] + " " +
                                                                        contcompare[i]["middle_name"] + " " + contcompare[i]["last_name"] + "\n" +
                                                                        compname["company_name"] + "\n" +
                                                                        compname["street"] + ", " + compname["suite"] + "\n" +
                                                                        compname["city"] + ", " + compname["state"] + " " + compname["zip"] +
                                                                        "\n\nDoes this contact match what you were planning on entering? \n" +
                                                                        "\nThere is a possibility this contact was added after your data pull so refresh \n" +
                                                                        "your data by closing/re-opening contacts after answering question.",
                                                                        "Contact Found", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

                                                                        switch (result)
                                                                        {
                                                                            case System.Windows.Forms.DialogResult.Yes:
                                                                                { this.Close(); }
                                                                                return;
                                                                            case System.Windows.Forms.DialogResult.No:
                                                                                {
                                                                                    if (i == count)
                                                                                    { return; }
                                                                                    break;
                                                                                }
                                                                            case System.Windows.Forms.DialogResult.Cancel:
                                                                                { this.Close(); }
                                                                                return;
                                                                        }
                                                                    }
                                                                    break;
                                                                case false:
                                                                    {
                                                                        var result = MessageBox.Show("There is (1) contact that match what you entered " +
                                                                        "in the first and last name boxes.\n\n" + contcompare[i]["first_name"] + " " +
                                                                        contcompare[i]["middle_name"] + " " + contcompare[i]["last_name"] + "\n" +
                                                                        compname["company_name"] + "\n" +
                                                                        compname["street"] + "\n" + compname["city"] + ", " +
                                                                        compname["state"] + " " + compname["zip"] +
                                                                        "\n\nDoes this contact match what you were planning on entering? \n" +
                                                                        "\nThere is a possibility this contact was added after your data pull so refresh \n" +
                                                                        "your data by closing/re-opening contacts after answering question.",
                                                                        "Contact Found", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

                                                                        switch (result)
                                                                        {
                                                                            case System.Windows.Forms.DialogResult.Yes:
                                                                                { this.Close(); }
                                                                                return;
                                                                            case System.Windows.Forms.DialogResult.No:
                                                                                {
                                                                                    if (i == count)
                                                                                    { return; }
                                                                                    break;
                                                                                }
                                                                            case System.Windows.Forms.DialogResult.Cancel:
                                                                                { this.Close(); }
                                                                                return;
                                                                        }
                                                                    }
                                                                    break;
                                                            }
                                                        }
                                                        break;
                                                }
                                            }
                                            break;
                                        default:
                                            {
                                                switch (tit)
                                                {
                                                    case true:
                                                        {
                                                            switch (suite)
                                                            {
                                                                case true:
                                                                    {
                                                                        var result = MessageBox.Show("There are (" + count + ") contacts that match what you entered " +
                                                                        "in the first and last name boxes.\n\nHere is " + (i + 1) + " of those " + count +
                                                                        " contacts.\n\n" + contcompare[i]["first_name"] + " " + contcompare[i]["middle_name"] + " " +
                                                                        contcompare[i]["last_name"] + "\n" + contcompare[i]["job_title"] + "\n" +
                                                                        compname["company_name"] + "\n" + compname["street"] + ", " + compname["suite"] + "\n" +
                                                                        compname["city"] + ", " + compname["state"] + " " + compname["zip"] +
                                                                        "\n\nDoes this contact match what you were planning on entering? \n" +
                                                                        "\nThere is a possibility this contact was added after your data pull so refresh \n" +
                                                                        "your data by closing/re-opening contacts after answering question.",
                                                                        "Contact Found", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

                                                                        switch (result)
                                                                        {
                                                                            case System.Windows.Forms.DialogResult.Yes:
                                                                                { this.Close(); }
                                                                                return;
                                                                            case System.Windows.Forms.DialogResult.No:
                                                                                {
                                                                                    if (i == count)
                                                                                    { return; }
                                                                                    break;
                                                                                }
                                                                            case System.Windows.Forms.DialogResult.Cancel:
                                                                                { this.Close(); }
                                                                                return;
                                                                        }
                                                                    }
                                                                    break;
                                                                case false:
                                                                    {
                                                                        var result = MessageBox.Show("There are (" + count + ") contacts that match what you entered " +
                                                                        "in the first and last name boxes.\n\nHere is " + (i + 1) + " of those " + count +
                                                                        " contacts.\n\n" + contcompare[i]["first_name"] + " " + contcompare[i]["middle_name"] + " " +
                                                                        contcompare[i]["last_name"] + "\n" + contcompare[i]["job_title"] + "\n" +
                                                                        compname["company_name"] + "\n" + compname["street"] + "\n" +
                                                                        compname["city"] + ", " + compname["state"] + " " + compname["zip"] +
                                                                        "\n\nDoes this contact match what you were planning on entering? \n" +
                                                                        "\nThere is a possibility this contact was added after your data pull so refresh \n" +
                                                                        "your data by closing/re-opening contacts after answering question.",
                                                                        "Contact Found", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

                                                                        switch (result)
                                                                        {
                                                                            case System.Windows.Forms.DialogResult.Yes:
                                                                                { this.Close(); }
                                                                                return;
                                                                            case System.Windows.Forms.DialogResult.No:
                                                                                {
                                                                                    if (i == count)
                                                                                    { return; }
                                                                                    break;
                                                                                }
                                                                            case System.Windows.Forms.DialogResult.Cancel:
                                                                                { this.Close(); }
                                                                                return;
                                                                        }
                                                                    }
                                                                    break;
                                                            }
                                                        }
                                                        break;
                                                    case false:
                                                        {
                                                            switch (suite)
                                                            {
                                                                case true:
                                                                    {
                                                                        var result = MessageBox.Show("There are (" + count + ") contacts that match what you entered " +
                                                                        "in the first and last name boxes.\n\nHere is " + (i + 1) + " of those " + count +
                                                                        " contacts.\n\n" + contcompare[i]["first_name"] + " " + contcompare[i]["middle_name"] + " " +
                                                                        contcompare[i]["last_name"] + "\n" + compname["company_name"] + "\n" +
                                                                        compname["street"] + ", " + compname["suite"] + "\n" + compname["city"] +
                                                                        ", " + compname["state"] + " " + compname["zip"] +
                                                                        "\n\nDoes this contact match what you were planning on entering? \n" +
                                                                        "\nThere is a possibility this contact was added after your data pull so refresh \n" +
                                                                        "your data by closing/re-opening contacts after answering question.",
                                                                        "Contact Found", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

                                                                        switch (result)
                                                                        {
                                                                            case System.Windows.Forms.DialogResult.Yes:
                                                                                { this.Close(); }
                                                                                return;
                                                                            case System.Windows.Forms.DialogResult.No:
                                                                                {
                                                                                    if (i == count)
                                                                                    { return; }
                                                                                    break;
                                                                                }
                                                                            case System.Windows.Forms.DialogResult.Cancel:
                                                                                { this.Close(); }
                                                                                return;
                                                                        }
                                                                    }
                                                                    break;
                                                                case false:
                                                                    {
                                                                        var result = MessageBox.Show("There are (" + count + ") contacts that match what you entered " +
                                                                        "in the first and last name boxes.\n\nHere is " + (i + 1) + " of those " + count +
                                                                        " contacts.\n\n" + contcompare[i]["first_name"] + " " + contcompare[i]["middle_name"] + " " +
                                                                        contcompare[i]["last_name"] + "\n" + compname["company_name"] + "\n" +
                                                                        compname["street"] + "\n" + compname["city"] + ", " +
                                                                        compname["state"] + " " + compname["zip"] +
                                                                        "\n\nDoes this contact match what you were planning on entering? \n" +
                                                                        "\nThere is a possibility this contact was added after your data pull so refresh \n" +
                                                                        "your data by closing/re-opening contacts after answering question.",
                                                                        "Contact Found", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

                                                                        switch (result)
                                                                        {
                                                                            case System.Windows.Forms.DialogResult.Yes:
                                                                                { this.Close(); }
                                                                                return;
                                                                            case System.Windows.Forms.DialogResult.No:
                                                                                {
                                                                                    if (i == count)
                                                                                    { return; }
                                                                                    break;
                                                                                }
                                                                            case System.Windows.Forms.DialogResult.Cancel:
                                                                                { this.Close(); }
                                                                                return;
                                                                        }
                                                                    }
                                                                    break;
                                                            }
                                                        }
                                                        break;
                                                }
                                            }
                                            break;
                                    }
                                }
                                break;

                            case false:
                                {
                                    switch (count)
                                    {
                                        case 1:
                                            {
                                                switch (tit)
                                                {
                                                    case true:
                                                        {
                                                            switch (suite)
                                                            {
                                                                case true:
                                                                    {
                                                                        var result = MessageBox.Show("There is (1) contact that match what you entered " +
                                                                        "in the first and last name boxes.\n\n" + contcompare[i]["first_name"] + " " +
                                                                        contcompare[i]["last_name"] + "\n" +
                                                                        contcompare[i]["job_title"] + "\n" + compname["company_name"] + "\n" +
                                                                        compname["street"] + ", " + compname["suite"] + "\n" +
                                                                        compname["city"] + ", " + compname["state"] + " " + compname["zip"] +
                                                                        "\n\nDoes this contact match what you were planning on entering? \n" +
                                                                        "\nThere is a possibility this contact was added after your data pull so refresh \n" +
                                                                        "your data by closing/re-opening contacts after answering question.",
                                                                        "Contact Found", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

                                                                        switch (result)
                                                                        {
                                                                            case System.Windows.Forms.DialogResult.Yes:
                                                                                { this.Close(); }
                                                                                return;
                                                                            case System.Windows.Forms.DialogResult.No:
                                                                                {
                                                                                    if (i == count)
                                                                                    { return; }
                                                                                    break;
                                                                                }
                                                                            case System.Windows.Forms.DialogResult.Cancel:
                                                                                { this.Close(); }
                                                                                return;
                                                                        }
                                                                    }
                                                                    break;
                                                                case false:
                                                                    {
                                                                        var result = MessageBox.Show("There is (1) contact that match what you entered " +
                                                                        "in the first and last name boxes.\n\n" + contcompare[i]["first_name"] + " " +
                                                                        contcompare[i]["last_name"] + "\n" +
                                                                        contcompare[i]["job_title"] + "\n" + compname["company_name"] + "\n" +
                                                                        compname["street"] + "\n" + compname["city"] + ", " +
                                                                        compname["state"] + " " + compname["zip"] +
                                                                        "\n\nDoes this contact match what you were planning on entering? \n" +
                                                                        "\nThere is a possibility this contact was added after your data pull so refresh \n" +
                                                                        "your data by closing/re-opening contacts after answering question.",
                                                                        "Contact Found", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

                                                                        switch (result)
                                                                        {
                                                                            case System.Windows.Forms.DialogResult.Yes:
                                                                                { this.Close(); }
                                                                                return;
                                                                            case System.Windows.Forms.DialogResult.No:
                                                                                {
                                                                                    if (i == count)
                                                                                    { return; }
                                                                                    break;
                                                                                }
                                                                            case System.Windows.Forms.DialogResult.Cancel:
                                                                                { this.Close(); }
                                                                                return;
                                                                        }
                                                                    }
                                                                    break;
                                                            }
                                                        }
                                                        break;
                                                    case false:
                                                        {
                                                            switch (suite)
                                                            {
                                                                case true:
                                                                    {
                                                                        var result = MessageBox.Show("There is (1) contact that match what you entered " +
                                                                        "in the first and last name boxes.\n\n" + contcompare[i]["first_name"] + " " +
                                                                        contcompare[i]["last_name"] + "\n" +
                                                                        compname["company_name"] + "\n" +
                                                                        compname["street"] + ", " + compname["suite"] + "\n" +
                                                                        compname["city"] + ", " + compname["state"] + " " + compname["zip"] +
                                                                        "\n\nDoes this contact match what you were planning on entering? \n" +
                                                                        "\nThere is a possibility this contact was added after your data pull so refresh \n" +
                                                                        "your data by closing/re-opening contacts after answering question.",
                                                                        "Contact Found", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

                                                                        switch (result)
                                                                        {
                                                                            case System.Windows.Forms.DialogResult.Yes:
                                                                                { this.Close(); }
                                                                                return;
                                                                            case System.Windows.Forms.DialogResult.No:
                                                                                {
                                                                                    if (i == count)
                                                                                    { return; }
                                                                                    break;
                                                                                }
                                                                            case System.Windows.Forms.DialogResult.Cancel:
                                                                                { this.Close(); }
                                                                                return;
                                                                        }
                                                                    }
                                                                    break;
                                                                case false:
                                                                    {
                                                                        var result = MessageBox.Show("There is (1) contact that match what you entered " +
                                                                        "in the first and last name boxes.\n\n" + contcompare[i]["first_name"] + " " +
                                                                        contcompare[i]["last_name"] + "\n" +
                                                                        compname["company_name"] + "\n" +
                                                                        compname["street"] + "\n" + compname["city"] + ", " +
                                                                        compname["state"] + " " + compname["zip"] +
                                                                        "\n\nDoes this contact match what you were planning on entering? \n" +
                                                                        "\nThere is a possibility this contact was added after your data pull so refresh \n" +
                                                                        "your data by closing/re-opening contacts after answering question.",
                                                                        "Contact Found", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

                                                                        switch (result)
                                                                        {
                                                                            case System.Windows.Forms.DialogResult.Yes:
                                                                                { this.Close(); }
                                                                                return;
                                                                            case System.Windows.Forms.DialogResult.No:
                                                                                {
                                                                                    if (i == count)
                                                                                    { return; }
                                                                                    break;
                                                                                }
                                                                            case System.Windows.Forms.DialogResult.Cancel:
                                                                                { this.Close(); }
                                                                                return;
                                                                        }
                                                                    }
                                                                    break;
                                                            }
                                                        }
                                                        break;
                                                }
                                            }
                                            break;
                                        default:
                                            {
                                                switch (tit)
                                                {
                                                    case true:
                                                        {
                                                            switch (suite)
                                                            {
                                                                case true:
                                                                    {
                                                                        var result = MessageBox.Show("There are (" + count + ") contacts that match what you entered " +
                                                                        "in the first and last name boxes.\n\nHere is " + (i + 1) + " of those " + count +
                                                                        " contacts.\n\n" + contcompare[i]["first_name"] + " " +
                                                                        contcompare[i]["last_name"] + "\n" + contcompare[i]["job_title"] + "\n" +
                                                                        compname["company_name"] + "\n" + compname["street"] + ", " + compname["suite"] + "\n" +
                                                                        compname["city"] + ", " + compname["state"] + " " + compname["zip"] +
                                                                        "\n\nDoes this contact match what you were planning on entering? \n" +
                                                                        "\nThere is a possibility this contact was added after your data pull so refresh \n" +
                                                                        "your data by closing/re-opening contacts after answering question.",
                                                                        "Contact Found", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

                                                                        switch (result)
                                                                        {
                                                                            case System.Windows.Forms.DialogResult.Yes:
                                                                                { this.Close(); }
                                                                                return;
                                                                            case System.Windows.Forms.DialogResult.No:
                                                                                {
                                                                                    if (i == count)
                                                                                    { return; }
                                                                                    break;
                                                                                }
                                                                            case System.Windows.Forms.DialogResult.Cancel:
                                                                                { this.Close(); }
                                                                                return;
                                                                        }
                                                                    }
                                                                    break;
                                                                case false:
                                                                    {
                                                                        var result = MessageBox.Show("There are (" + count + ") contacts that match what you entered " +
                                                                        "in the first and last name boxes.\n\nHere is " + (i + 1) + " of those " + count +
                                                                        " contacts.\n\n" + contcompare[i]["first_name"] + " " +
                                                                        contcompare[i]["last_name"] + "\n" + contcompare[i]["job_title"] + "\n" +
                                                                        compname["company_name"] + "\n" + compname["street"] + "\n" +
                                                                        compname["city"] + ", " + compname["state"] + " " + compname["zip"] +
                                                                        "\n\nDoes this contact match what you were planning on entering? \n" +
                                                                        "\nThere is a possibility this contact was added after your data pull so refresh \n" +
                                                                        "your data by closing/re-opening contacts after answering question.",
                                                                        "Contact Found", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

                                                                        switch (result)
                                                                        {
                                                                            case System.Windows.Forms.DialogResult.Yes:
                                                                                { this.Close(); }
                                                                                return;
                                                                            case System.Windows.Forms.DialogResult.No:
                                                                                {
                                                                                    if (i == count)
                                                                                    { return; }
                                                                                    break;
                                                                                }
                                                                            case System.Windows.Forms.DialogResult.Cancel:
                                                                                { this.Close(); }
                                                                                return;
                                                                        }
                                                                    }
                                                                    break;
                                                            }
                                                        }
                                                        break;
                                                    case false:
                                                        {
                                                            switch (suite)
                                                            {
                                                                case true:
                                                                    {
                                                                        var result = MessageBox.Show("There are (" + count + ") contacts that match what you entered " +
                                                                        "in the first and last name boxes.\n\nHere is " + (i + 1) + " of those " + count +
                                                                        " contacts.\n\n" + contcompare[i]["first_name"] + " " +
                                                                        contcompare[i]["last_name"] + "\n" + compname["company_name"] + "\n" +
                                                                        compname["street"] + ", " + compname["suite"] + "\n" + compname["city"] +
                                                                        ", " + compname["state"] + " " + compname["zip"] +
                                                                        "\n\nDoes this contact match what you were planning on entering? \n" +
                                                                        "\nThere is a possibility this contact was added after your data pull so refresh \n" +
                                                                        "your data by closing re-opening contacts after answering question.",
                                                                        "Contact Found", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

                                                                        switch (result)
                                                                        {
                                                                            case System.Windows.Forms.DialogResult.Yes:
                                                                                { this.Close(); }
                                                                                return;
                                                                            case System.Windows.Forms.DialogResult.No:
                                                                                {
                                                                                    if (i == count)
                                                                                    { return; }
                                                                                    break;
                                                                                }
                                                                            case System.Windows.Forms.DialogResult.Cancel:
                                                                                { this.Close(); }
                                                                                return;
                                                                        }
                                                                    }
                                                                    break;
                                                                case false:
                                                                    {
                                                                        var result = MessageBox.Show("There are (" + count + ") contacts that match what you entered " +
                                                                        "in the first and last name boxes.\n\nHere is " + (i + 1) + " of those " + count +
                                                                        " contacts.\n\n" + contcompare[i]["first_name"] + " " +
                                                                        contcompare[i]["last_name"] + "\n" + compname["company_name"] + "\n" +
                                                                        compname["street"] + "\n" + compname["city"] + ", " +
                                                                        compname["state"] + " " + compname["zip"] +
                                                                        "\n\nDoes this contact match what you were planning on entering? \n" +
                                                                        "\nThere is a possibility this contact was added after your data pull so refresh \n" +
                                                                        "your data by closing/re-opening contacts after answering question.",
                                                                        "Contact Found", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

                                                                        switch (result)
                                                                        {
                                                                            case System.Windows.Forms.DialogResult.Yes:
                                                                                { this.Close(); }
                                                                                return;
                                                                            case System.Windows.Forms.DialogResult.No:
                                                                                {
                                                                                    if (i == count)
                                                                                    { return; }
                                                                                    break;
                                                                                }
                                                                            case System.Windows.Forms.DialogResult.Cancel:
                                                                                { this.Close(); }
                                                                                return;
                                                                        }
                                                                    }
                                                                    break;
                                                            }
                                                        }
                                                        break;
                                                }
                                            }
                                            break;
                                    }
                                }
                                break;
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                string subject = "ContactForm Last Name Leave Error";
                ErrorHandling.ErrorEmail(subject, ex);
            }
        }

        private void tbo_last_name_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Return)
            {ProcessTabKey(true);}
        }
        private void tbo_job_title_Leave(object sender, EventArgs e)
        {
            try
            {
                if (tbo_job_title.Text.Length >= 1)
                {
                    int i;
                    string s = tbo_job_title.Text.Trim();
                    string[] sa = s.Split(' ');
                    for (i = 0; i < sa.Length; i++)
                    {
                        sa[i] = sa[i].Substring(0, 1).ToUpper() + sa[i].Substring(1);
                        string jt = string.Join(" ", sa);
                        tbo_job_title.Text = jt;
                    }
                }
            }
            catch (System.Exception ex)
            {
                string subject = "ContactForm Title Leave Error";
                ErrorHandling.ErrorEmail(subject, ex);
            }
        }

        private void tbo_job_title_KeyPress(object sender, KeyPressEventArgs e)
      {
            if (e.KeyChar == (char)Keys.Return)
            {ProcessTabKey(true);}

            if (!Regex.IsMatch(tbo_job_title.Text, @"^[a-zA-Z&'.\s]{1,30}$") && !String.IsNullOrEmpty(tbo_job_title.Text))
            {
                MessageBox.Show("You have entered invalid characters or length > 25.  " +
                     "Permissible non-alpha characters are (' &).  " +
                     "Please re-enter the information.", "Invalid Characters", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                tbo_job_title.Clear();
                tbo_job_title.Focus();
            }            
        }

        private void cbo_company_Click(object sender, EventArgs e)
        {cbo_company.DisplayMember = "companies.comp_sel";}        
        
        private void tbo_d1_TextChanged(object sender, EventArgs e)
        {
            digit = tbo_d1.Text;
            if (func.d3(tbo_d1.Text))
                if (!Regex.IsMatch(tbo_d1.Text, @"^[0-9]{1,3}$") && !String.IsNullOrEmpty(tbo_d1.Text))
                {
                    MessageBox.Show("You have entered invalid characters.  " +
                         "Permissible (3) numeric characters.  " +
                         "Please re-enter the information.", "Invalid Characters", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    tbo_d1.Clear();
                    tbo_d1.Focus();
                }
                else
                { ProcessTabKey(true); }            
        }

        private void tbo_d2_TextChanged(object sender, EventArgs e)
        {
            digit = tbo_d2.Text;
            if (func.d3(tbo_d2.Text))
                if (!Regex.IsMatch(tbo_d2.Text, @"^[0-9]{1,3}$") && !String.IsNullOrEmpty(tbo_d2.Text))
                {
                    MessageBox.Show("You have entered invalid characters.  " +
                         "Permissible (3) numeric characters.  " +
                         "Please re-enter the information.", "Invalid Characters", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    tbo_d2.Clear();
                    tbo_d2.Focus();
                }
                else
                { ProcessTabKey(true); }   
        }

        private void tbo_d3_TextChanged(object sender, EventArgs e)
        {
            digit = tbo_d3.Text;
            if (func.d4(tbo_d3.Text))
                if (!Regex.IsMatch(tbo_d3.Text, @"^[0-9]{1,4}$") && !String.IsNullOrEmpty(tbo_d3.Text))
                {
                    MessageBox.Show("You have entered invalid characters.  " +
                         "Permissible (4) numeric characters.  " +
                         "Please re-enter the information.", "Invalid Characters", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    tbo_d3.Clear();
                    tbo_d3.Focus();
                }
                else
                { ProcessTabKey(true); }   
        }

        private void tbo_m1_TextChanged(object sender, EventArgs e)
        {
            digit = tbo_m1.Text;
            if (func.d3(tbo_m1.Text))
                if (!Regex.IsMatch(tbo_m1.Text, @"^[0-9]{1,3}$") && !String.IsNullOrEmpty(tbo_m1.Text))
                {
                    MessageBox.Show("You have entered invalid characters.  " +
                         "Permissible (3) numeric characters.  " +
                         "Please re-enter the information.", "Invalid Characters", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    tbo_m1.Clear();
                    tbo_m1.Focus();
                }
                else
                { ProcessTabKey(true); }   
        }

        private void tbo_m2_TextChanged(object sender, EventArgs e)
        {
            digit = tbo_m2.Text;
            if (func.d3(tbo_m2.Text))
                if (!Regex.IsMatch(tbo_m1.Text, @"^[0-9]{1,3}$") && !String.IsNullOrEmpty(tbo_m1.Text))
                {
                    MessageBox.Show("You have entered invalid characters.  " +
                         "Permissible (3) numeric characters.  " +
                         "Please re-enter the information.", "Invalid Characters", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    tbo_m1.Clear();
                    tbo_m1.Focus();
                }
                else
                { ProcessTabKey(true); }   
        }

        private void tbo_m3_TextChanged(object sender, EventArgs e)
        {
            digit = tbo_m3.Text;
            if (func.d4(tbo_m3.Text))
                if (!Regex.IsMatch(tbo_d3.Text, @"^[0-9]{1,4}$") && !String.IsNullOrEmpty(tbo_d3.Text))
                {
                    MessageBox.Show("You have entered invalid characters.  " +
                         "Permissible (4) numeric characters.  " +
                         "Please re-enter the information.", "Invalid Characters", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                    tbo_d3.Clear();
                    tbo_d3.Focus();
                }
                else
                { ProcessTabKey(true); }   
        }

        private void tbo_email_Leave(object sender, EventArgs e)
        {
            if (!Regex.IsMatch(tbo_email.Text, @"^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$") && !String.IsNullOrEmpty(tbo_email.Text))
            {
                MessageBox.Show("Email is incorrectly formatted.  Should be someone@example.com.  " +
                     "Please re-enter the information.", "Incorrect Format", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                tbo_email.Clear();
            }            
            else
            {
                return;            
            }
        }

        private void tbo_email_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Return)
            { ProcessTabKey(true); }
        }

        void ContactsAddEdit_Load(object sender, System.EventArgs e)
        {
            //throw new System.NotImplementedException();
        }        

        void compf_Load(object sender, EventArgs e)
        {}

        public ContactsAddEdit()
        {
            // TODO: Complete member initialization
        }

        public void but_editcomp_Click(object sender, EventArgs e)
        {
            if (cbo_company.SelectedIndex == -1)
            {
                MessageBox.Show("There must be a company name showing in the company drop down box.","Missing Company Name",MessageBoxButtons.OK);
                return;
            }
            //compsi = cbo_company.SelectedIndex;
            compsv = (int)cbo_company.SelectedValue;
            compe = new CompaniesAddEdit(dscont, compbs, compsv, dgv);
            compe.ShowDialog();

            //compe.FormClosed += new FormClosedEventHandler(compe_FormClosed);
            //compe.FormClosing += new FormClosingEventHandler(compe_FormClosing);
        }

        public void but_addcomp_Click(object sender, EventArgs e)
        {
            compsi = cbo_company.SelectedIndex;
            compe = new CompaniesAddEdit(dscont, compbs, "companies", dgv);
            compe.ShowDialog();                       
        }

        private void but_save_Click(object sender, EventArgs e)
        {
            try
            {               
                if (pos == 0)
                {
                    if (dgv == null)
                    {
                        cbo_contsel.SelectedIndexChanged -= new EventHandler(cbo_contsel_SelectedIndexChanged);
                        
                    }
                    newcont = true;
                    cont = dscont.Tables["contacts"].NewRow();                   
                    dscont.Tables["contacts"].Rows.InsertAt(cont, 0);
                    cbo_contsel.SelectedIndex = -1;
                    pos = (int)cont.ItemArray[0];                                      
                }

                else if (pos != 0)
                {
                    cbo_contsel.SelectedIndexChanged -= new EventHandler(cbo_contsel_SelectedIndexChanged);
                    cont = dscont.Tables["contacts"].Rows.Find(pos);                    
                    cont["contact_id"] = pos;
                    cont.BeginEdit();
                }

                try
                {
                    bool fn = (!String.IsNullOrEmpty(tbo_first_name.Text));
                    switch (fn)
                    {
                        case true:
                            { cont["first_name"] = tbo_first_name.Text; }
                            break;
                        case false:
                            {
                                tbo_first_name.BackColor = Color.Red;
                                but_save.Enabled = false;
                            }
                            break;
                    }

                    if (!String.IsNullOrEmpty(tbo_middle_name.Text))
                    { cont["middle_name"] = tbo_middle_name.Text; }
                    else
                    { cont["middle_name"] = ""; }

                    bool ln = (!String.IsNullOrEmpty(tbo_last_name.Text));
                    switch (ln)
                    {
                        case true:
                            { cont["last_name"] = tbo_last_name.Text; }
                            break;
                        case false:
                            {
                                tbo_last_name.BackColor = Color.Red;
                                but_save.Enabled = false;
                            }
                            break;
                    }

                    bool jt = (!String.IsNullOrEmpty(tbo_job_title.Text));
                    {
                        switch (jt)
                        {
                            case true:
                                { cont["job_title"] = tbo_job_title.Text; }
                                break;

                            case false:
                                {
                                    tbo_job_title.BackColor = Color.Green;

                                    switch (Mess.buttonresult)
                                    {
                                        case "no":
                                            {
                                                cont["job_title"] = "";
                                                //tbo_job_title.BackColor = Color.White;
                                            }
                                            break;
                                    }
                                }
                                break;
                        }
                    }

                    bool cn = (cbo_company.SelectedValue != null);
                    {
                        switch (cn)
                        {
                            case true:
                                {
                                    DataRow comp = dscont.Tables["companies"].Rows.Find(cbo_company.SelectedValue);
                                    cont["company_id"] = comp["company_id"];
                                }
                                break;

                            case false:
                                {
                                    cbo_company.BackColor = Color.Red;
                                    but_save.Enabled = false;
                                }
                                break;
                        }
                    }

                    bool directnumber = !String.IsNullOrEmpty(tbo_d1.Text) && !String.IsNullOrEmpty(tbo_d2.Text) && !String.IsNullOrEmpty(tbo_d3.Text);

                    switch (directnumber)
                    {                 
                        case true:
                            {
                                bool ext = String.IsNullOrEmpty(tbo_d4.Text.Trim());

                                switch (ext)
                                {
                                    case true:
                                        { cont["direct_phone"] = "(" + tbo_d1.Text + ")" + " " + tbo_d2.Text + "-" + tbo_d3.Text; }
                                        break;
                                    case false:
                                        { cont["direct_phone"] = "(" + tbo_d1.Text + ")" + " " + tbo_d2.Text + "-" + tbo_d3.Text + "  Ext: " + tbo_d4.Text; }
                                        break;
                                }
                            }
                            break;
                        case false:
                            {
                                tbo_d1.BackColor = Color.Green;
                                tbo_d2.BackColor = Color.Green;
                                tbo_d3.BackColor = Color.Green;                                
                                
                                switch (Mess.buttonresult)
                                {
                                    case "no":
                                            {
                                                cont["direct_phone"] = "";
                                            }
                                        break;
                                }
                            }
                            break;
                    }

                    bool mobile = !String.IsNullOrEmpty(tbo_m1.Text) && !String.IsNullOrEmpty(tbo_m2.Text) && !String.IsNullOrEmpty(tbo_m3.Text);

                    switch (mobile)
                    {
                        case true:
                            { cont["mobile_phone"] = "(" + tbo_m1.Text + ")" + " " + tbo_m2.Text + "-" + tbo_m3.Text; }
                            break;
                        case false:
                            {
                                tbo_m1.BackColor = Color.Green;
                                tbo_m2.BackColor = Color.Green;
                                tbo_m3.BackColor = Color.Green;                                
                                
                                switch (Mess.buttonresult)
                                {
                                    case "no":
                                        {
                                            cont["mobile_phone"] = null;
                                        }
                                        break;
                                }
                            }
                            break;
                    }

                    bool em = (!String.IsNullOrEmpty(tbo_email.Text));
                    {
                        switch (em)
                        {
                            case true:
                                { cont["email"] = tbo_email.Text; }
                                break;

                            case false:
                                {
                                    tbo_email.BackColor = Color.Red;
                                    but_save.Enabled = false;
                                }
                                break;
                        }
                    }

                    try
                    {
                        cont["timestamp"] = DateTime.Now;
                        cont["user"] = System.Environment.UserName;
                    }

                    catch (System.Exception ex)
                    {
                        string subject = "ContactForm Timestamp/User Error";
                        ErrorHandling.ErrorEmail(subject, ex);
                    }

                    if (String.IsNullOrEmpty(tbo_middle_name.Text))
                    { cont["full_name"] = tbo_first_name.Text + " " + tbo_last_name.Text; }
                    else
                    { cont["full_name"] = tbo_first_name.Text + " " + tbo_middle_name.Text + " " + tbo_last_name.Text; }                    

                    if ((String.IsNullOrEmpty(tbo_first_name.Text) || String.IsNullOrEmpty(tbo_last_name.Text) ||
                        cbo_company.SelectedValue == null ||  String.IsNullOrEmpty(tbo_email.Text)) && (String.IsNullOrEmpty(tbo_job_title.Text) ||
                        String.IsNullOrEmpty(tbo_d1.Text) || String.IsNullOrEmpty(tbo_d2.Text) || String.IsNullOrEmpty(tbo_d3.Text) ||
                        String.IsNullOrEmpty(tbo_m1.Text) || String.IsNullOrEmpty(tbo_m2.Text) || String.IsNullOrEmpty(tbo_m3.Text)))
                    {
                        condition = "par";
                        mess = new Mess(condition);
                        mess.Load += new EventHandler(mess_Load);
                        mess.FormClosing += new FormClosingEventHandler(mess_FormClosing);
                        cbo_contsel.SelectedIndex = -1;
                        mess.ShowDialog();
                        return;                    
                    }

                    else if ((String.IsNullOrEmpty(tbo_first_name.Text) || String.IsNullOrEmpty(tbo_last_name.Text) ||
                        cbo_company.SelectedValue == null || String.IsNullOrEmpty(tbo_email.Text)) && (!String.IsNullOrEmpty(tbo_job_title.Text) ||
                        !String.IsNullOrEmpty(tbo_d1.Text) || !String.IsNullOrEmpty(tbo_d2.Text) || !String.IsNullOrEmpty(tbo_d3.Text) ||
                        !String.IsNullOrEmpty(tbo_m1.Text) || !String.IsNullOrEmpty(tbo_m2.Text) || !String.IsNullOrEmpty(tbo_m3.Text)))
                    {
                        condition = "r";
                        mess = new Mess(condition);
                        mess.Load += new EventHandler(mess_Load);
                        mess.FormClosing += new FormClosingEventHandler(mess_FormClosing);
                        cbo_contsel.SelectedIndex = -1;
                        mess.ShowDialog();
                        return;
                    }

                    else if ((!String.IsNullOrEmpty(tbo_first_name.Text) || !String.IsNullOrEmpty(tbo_last_name.Text) ||
                        cbo_company.SelectedValue != null || !String.IsNullOrEmpty(tbo_email.Text)) && (String.IsNullOrEmpty(tbo_job_title.Text) ||
                        String.IsNullOrEmpty(tbo_d1.Text) || String.IsNullOrEmpty(tbo_d2.Text) || String.IsNullOrEmpty(tbo_d3.Text) ||
                        String.IsNullOrEmpty(tbo_m1.Text) || String.IsNullOrEmpty(tbo_m2.Text) || String.IsNullOrEmpty(tbo_m3.Text)))
                    {
                        if (pref != 1)
                        {
                            pref = 1;
                            condition = "p";
                            mess = new Mess(condition);
                            mess.Load += new EventHandler(mess_Load);
                            mess.FormClosing += new FormClosingEventHandler(mess_FormClosing);
                            cbo_contsel.SelectedIndex = -1;
                            mess.ShowDialog();                            
                            return;
                        }
                        else if (pref == 1)
                        {
                            this.Dispose();
                        }
                    }
                    cont.EndEdit();
                    
                    connect.Connect("contacts");
                    connect.LoadContactsComp(pos, ref currentcont);
                    if (currentcont.Rows.Count != 0)
                    {
                        currentrow = currentcont.Rows[0];
                    }
                    MySqlConn con = new MySqlConn(dscont, dscont.Tables["contacts"]);
                    con.StatmentCompleted += new MySqlConn.SaveStatementComplete(con_StatmentCompleted);
                    connect.StatmentCompleted += new MySqlConn.SaveStatementComplete(con_StatmentCompleted);
                    connect.MysqlPreSave(dscont, dscont.Tables["contacts"], dgv, cont, currentrow, pos, pulltime);
                    connect.Disconnect();                    
                    this.Dispose();
                    if (dgv != null)
                    {
                        int sel = dgv.NewRowIndex;
                        dgv.Rows[sel].Cells[0].Selected = true;
                    }
                }

                catch (System.Exception ex)
                {
                    string subject = "ContactForm Creating Contact Error";
                    ErrorHandling.ErrorEmail(subject, ex);
                }
            }
            catch (System.Exception ex)
            {
                string subject = "ContactForm Global Error";
                ErrorHandling.ErrorEmail(subject, ex);                       
            }
        }

        void mess_FormClosing(object sender, FormClosingEventArgs e)
        {
            Mess mess = (Mess)sender;

            switch(condition)
            {
                case "par":
                    {
                        if (Mess.buttonresult == "ok")
                                {
                                    cbo_contsel.SelectedIndex = -1;
                                    tbo_first_name.BackColor = Color.White;
                                    tbo_last_name.BackColor = Color.White;
                                    tbo_job_title.BackColor = Color.White;
                                    cbo_company.BackColor = Color.White;
                                    tbo_d1.BackColor = Color.White;
                                    tbo_d2.BackColor = Color.White;
                                    tbo_d3.BackColor = Color.White;
                                    tbo_m1.BackColor = Color.White;
                                    tbo_m2.BackColor = Color.White;
                                    tbo_m3.BackColor = Color.White;
                                    tbo_email.BackColor = Color.White;
                                    but_save.Enabled = true;
                                }
                                return;                            
                        }                    
                case "r":
                    {
                        if (Mess.buttonresult == "ok")
                                {
                                    cbo_contsel.SelectedIndex = -1;
                                    tbo_first_name.BackColor = Color.White;
                                    tbo_last_name.BackColor = Color.White;
                                    cbo_company.BackColor = Color.White;                                    
                                    tbo_email.BackColor = Color.White;
                                    but_save.Enabled = true;
                                }
                                return;    
                        }
                    
                case "p":
                    {
                        switch (Mess.buttonresult)
                        {
                            case "yes":
                                {
                                    cbo_contsel.SelectedIndex = -1;
                                    tbo_job_title.BackColor = Color.White;                                    
                                    tbo_d1.BackColor = Color.White;
                                    tbo_d2.BackColor = Color.White;
                                    tbo_d3.BackColor = Color.White;
                                    tbo_m1.BackColor = Color.White;
                                    tbo_m2.BackColor = Color.White;
                                    tbo_m3.BackColor = Color.White;
                                }
                                return;
                            
                            case "no":
                                {
                                    but_save.PerformClick();
                                }
                                break;
                        }
                    }
                    break;
            }
        }

        void mess_Load(object sender, EventArgs e)
        { mess.Load -= new EventHandler(mess_Load); }


        void con_StatmentCompleted(string SqlStatement)
        {}

        public void but_cancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void cbo_company_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            MessageBox.Show("this works");
        }

        #endregion

        public DataSet contacts { get; set; }

        public BindingSource contactsbs { get; set; }

        private void label9_Click(object sender, EventArgs e)
        {}

        private void ContactsAddEdit_FormClosing()
        {}

        internal void but_cancel_Click()
        {}
    }
}